import { onBeforeUnmount } from 'vue'
/* Echarts图表尺寸自适应 */
export const fitChartSize = (size: number, defalteWidth = 1920) => {
  const clientWidth =
    window.innerWidth ||
    document.documentElement.clientWidth ||
    document.body.clientWidth
  if (!clientWidth) return size
  const scale = clientWidth / defalteWidth
  return Number((size * scale).toFixed(3))
}

const startMarquee = (
  marqueeObj: string | HTMLElement,
  lh: number | string,
  speed = 20,
  delay = 1000
) => {
  //lh---每行列表的高度，speed---滚动的速度，delay---间隔多久滚动一次,marqueeObj---需要实现这个效果的id
  let p = false
  let t: any
  let o: HTMLElement
  if (typeof marqueeObj === 'string') {
    o = document.getElementsByClassName(marqueeObj)[0] as HTMLElement
  } else {
    return new Error('所给参数不正确')
  }
  if (o?.style) {
    o.innerHTML += o.innerHTML
    o.style.marginTop = (0).toString()
    o.onmouseover = function () {
      p = true
    } //鼠标移入，停止滚动
    o.onmouseout = function () {
      p = false
    } //鼠标移出，继续滚动
    if (typeof lh === 'string') {
      const child = o.querySelector(lh)
      lh = child?.clientHeight || 40
    }
  }

  function start() {
    if (typeof t === 'number') clearInterval(t)

    t = setInterval(scrolling, speed) //定时器，自动滚动
    if (!p && o?.style)
      o.style.marginTop = parseInt(o.style.marginTop) - 1 + 'px'
  }

  function scrolling() {
    if (o?.style) {
      if (parseInt(o.style.marginTop) % Number(lh) != 0) {
        o.style.marginTop = parseInt(o.style.marginTop) - 1 + 'px'
        if (Math.abs(parseInt(o.style.marginTop)) >= o.scrollHeight / 2)
          o.style.marginTop = 0 + ''
      } else {
        clearInterval(t)
        t = undefined
        setTimeout(start, delay)
      }
    }
  }

  setTimeout(start, delay)
  onBeforeUnmount(() => {
    clearInterval(t)
  })
}

/**
 * 电子地图
 * @param type
 */
const setMapMode = (type = 0, style = 'satellite-v9') => {
  if (type == -1) {
    __g.settings.setMapMode(0, {})
  } else {
    //使用mapbox 设置大地图模式
    __g.settings.setMapMode(
      2,
      {
        coordType: 0, //坐标系类型，0：经纬度；1：本地（默认值是0）
        serviceType: 4, //服务类型，0：MVT矢量切片（默认值）； 1：WMTS(ArcGIS)； 2：WMS； 3：MapServer(ArcGIS) ； 4：Mapbox
        mapPoint: [618999.9375, 2721147.75], //同名点，取值范围：[x,y]，（默认值是[0, 0]）
        longitude: 118.174877, //经度，取值范围：[0~180]（默认值是0.0）
        latitude: 24.590013, //纬度，取值范围：[0~90]（默认值是0.0）
        style: `mapbox://styles/mapbox/${style}`, //风格路径，字符串地址，（默认值是 "mapbox://styles/mapbox/streets-v10"）
        coordOrder: 0, //坐标顺序，0: XY; 1: YX（默认值为0）
        cache: ':memory:', //缓存路径，字符串地址，（默认值是 ":memory:"）
        renderMode: 0, //渲染模式，0：正常；1：透明；2：标注；3：贴地（默认值是0）
        groundHeight: 1, //地面高度，取值范围：[0~任意数值]（默认值是0.0）
      },
      () => {
        console.log('设置大地图模式完成')
      }
    )
  }
}

const num = 180
/**
 * 圆形
 * @param center
 * @param radius
 */
const getCircular = (center: number[], radius: number) => {
  //半径
  const r = 150 //单位：米
  //待计算圆上的点 注意：半径越大需要计算的点数量越多 本示例使用360个点
  const pointArr = []
  for (let i = 0; i <= num; i++) {
    //角度转弧度
    const radians = (i * (360 / num) * Math.PI) / 180
    //计算圆上的点X坐标
    const x1 = center[0] + radius * Math.cos(radians)
    //计算圆上的点Y坐标
    const y1 = center[1] + radius * Math.sin(radians)
    //赋值圆上所有点数组
    pointArr.push([x1, y1, center[2]])
  }
  return pointArr
}

/**
 * 椭圆
 * @param center
 * @param longRadius 长轴
 * @param shortRadius 短轴
 */
const getEllipse = (
  center: Array<number>,
  longRadius = 50,
  shortRadius = 50,
  angle = 0
) => {
  //待计算圆上的点 注意：半径越大需要计算的点数量越多 本示例使用360个点
  const data = []
  for (let index = 0; index < 360; index++) {
    let x = longRadius * Math.cos((Math.PI * 2 * index) / 360)
    let y = shortRadius * Math.sin((Math.PI * 2 * index) / 360)
    let a = center[0]
    let b = center[1]
    let x0 = x + center[0]
    let y0 = y + center[1]
    let rx =
      a +
      (x0 - a) * Math.cos((angle * Math.PI) / 180) -
      (y0 - b) * Math.sin((angle * Math.PI) / 180)
    let ry =
      b +
      (x0 - a) * Math.sin((angle * Math.PI) / 180) +
      (y0 - b) * Math.cos((angle * Math.PI) / 180)
    data.push([rx, ry, center[2]])
  }
  return data
}

/**
 * 颜色转换 从 eg[255,255,255]转为平台颜色[1,1,1]
 * @param colorArr 颜色数组
 * @param opacity 透明度
 */
const getColorConversion = (colorArr: number[], opacity = 1) => {
  return [colorArr[0] / 255, colorArr[1] / 255, colorArr[2] / 255, opacity]
}

/**
 *延迟函数
 *@param time 时间
 */
const delay = (time: number) => {
  return new Promise<void>((resolve) => {
    const timer = setTimeout(() => {
      clearTimeout(timer)
      resolve()
    }, time)
  })
}

/**
 * hex转rgb颜色值
 */
const hexToRgb = (hex: any) => {
  const rgb = []
  for (let i = 1; i < 7; i += 2) {
    rgb.push(parseInt('0x' + hex.slice(i, i + 2)))
  }
  return rgb
}

/**
 * 获取随机整数
 */
const getRandNumBetween = (min: number, max: number) => {
  return Math.floor(Math.random() * (max - min) + min)
}
/**
 * 获取渐变颜色组
 */
const gradient = (startColor: any, endColor: any, step: any) => {
  // 将 hex 转换为rgb
  const sColor = hexToRgb(startColor)
  const eColor = hexToRgb(endColor)

  // 计算R\G\B每一步的差值
  const rStep = (eColor[0] - sColor[0]) / step
  const gStep = (eColor[1] - sColor[1]) / step
  const bStep = (eColor[2] - sColor[2]) / step

  const gradientColorArr = []
  for (var i = 0; i < step; i++) {
    // 计算每一步的hex值
    gradientColorArr.push([
      (rStep * i + sColor[0]) / 255,
      (gStep * i + sColor[1]) / 255,
      (bStep * i + sColor[2]) / 255,
      0.5,
    ])
  }
  return gradientColorArr
}
/**
 * 超长变成...
 */
const showTitleExtend = (title: string, len: number) => {
  if (title.length > len) {
    return title.substr(0, len - 1) + '...'
  }
  return title
}
const phoneString = (phoneNumber: any) => {
  return phoneNumber.replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3')
}
const escapeString = (date: number) => {
  switch (date) {
    case 0:
      return '天'
    case 1:
      return '一'
    case 2:
      return '二'
    case 3:
      return '三'
    case 4:
      return '四'
    case 5:
      return '五'
    case 6:
      return '六'
    default:
      return '一'
  }
}
export {
  gradient,
  phoneString,
  getRandNumBetween,
  hexToRgb,
  startMarquee,
  setMapMode,
  getCircular,
  getEllipse,
  getColorConversion,
  delay,
  showTitleExtend,
  escapeString,
}
